package demo.mina.util;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * <p>Description:  </p>
 *
 * @author zhonghaijun
 * @email "mailto:iamxiaohaijun@gmail.com"
 * @date 2022.04.06 10:06
 */
public class ClassUtils {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String packageName = "com.zhj";
        Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(packageName.replace(".", "/"));
        Set<Class<?>> set = new HashSet<>();
        while (resources.hasMoreElements()) {
            URL nextElement = resources.nextElement();
            String file = nextElement.getFile();
            process(file, packageName, set);
        }
        System.out.println(set);
    }

    public static void process(String classPath, String rootPackageName, Set<Class<?>> classSet) throws ClassNotFoundException {
        File file = new File(classPath);
        if (!file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null) {
                return;
            }
            for (File childrenFile : files) {
                if (childrenFile.isDirectory()) {
                    process(childrenFile.getAbsolutePath(), rootPackageName + "." + childrenFile.getName(), classSet);
                } else {
                    process(childrenFile.getAbsolutePath(), rootPackageName, classSet);
                }
            }
        } else {
            String fileName = file.getName();
            boolean endsWith = fileName.endsWith(".class");
            if (endsWith) {
                fileName = fileName.substring(0, fileName.length() - 6);
                Class<?> loadClass = Thread.currentThread().getContextClassLoader().loadClass(rootPackageName + "." + fileName);
                classSet.add(loadClass);
            }
        }
    }

}
